package com.fbooks.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.fbooks.bean.Article;
import com.fbooks.bean.ArticleComment;
import com.fbooks.bean.User;
import com.fbooks.mapper.ArticleCommentMapper;
import com.fbooks.mapper.ArticleMapper;
import com.fbooks.mapper.UserMapper;
import com.fbooks.service.ArticleCommontService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: LuoRunFeng
 * @Email: 475403147@qq.com
 * @Time: 2020/5/28 0028 22:08
 * @Team: 蜂鸟工作室
 */
@Service
public class ArticleCommontServiceImpl implements ArticleCommontService {

    @Autowired
    private ArticleCommentMapper articleCommentMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 评论发布
     * @param articleComment
     */
    public JSONObject releaseCommont(ArticleComment articleComment) {
        JSONObject jsonObject = new JSONObject();
        int i = articleCommentMapper.insertSelective(articleComment);
        if (i ==1){
            //返回发表评论者的信息
            User userInfo = userMapper.backUserInfo(articleComment.getUserId());
            System.out.println(userInfo);
            jsonObject.put("userInfo",userInfo);
            jsonObject.put("isSuccess",true);
        }else {
            jsonObject.put("isSuccess",false);
            jsonObject.put("Info","评论失败");
        }
        return jsonObject;
    }

    @Override
    public List<JSONObject> getCommentByUid(String uid) {
        List<JSONObject> listInfo = new ArrayList<JSONObject>();

        Example example = new Example(ArticleComment.class);
        example.createCriteria().andEqualTo("userId",uid);
        List<ArticleComment> articleComments = articleCommentMapper.selectByExample(example);
//        System.out.println(articleComments);
        for (ArticleComment articleComment : articleComments) {
           String userId = articleComment.getUserId();
           String articleId = articleComment.getArticleId();

           JSONObject info = new JSONObject();
            info.put("createTime",articleComment.getCreateTime());
            info.put("CommentContent",articleComment.getCommentContent());

            //获取文章title
            Article article = articleMapper.selectByPrimaryKey(articleId);
            info.put("title",article.getTitle());

            //获取用户名
            User user = userMapper.getUserInfoById(userId);
            info.put("username",user.getUsername());

            listInfo.add(info);
        }
        return listInfo;
    }
}
